import { useEffect, useRef, useState } from "react"
export type pageType = { pageSize: number; pageNum: number }
const usePagination = (pageSize?: number) => {
	// eslint-disable-next-line @typescript-eslint/no-unused-vars
	const pageReq = useRef((_pageinfo: pageType) => {})
	const [needSubmit, setNeedSubmit] = useState(true)
	const [pagination, setPage] = useState({
		pageNum: 1,
		pageSize: pageSize ?? 100
	})
	const onPageChange = (page: { pageSize: number; current: number }) => {
		setNeedSubmit(true)
		if (page)
			setPage({
				pageNum: page.current,
				pageSize: page.pageSize
			})
	}
	const resetPagination = (submit: (pageInfo: pageType) => void) => {
		setNeedSubmit(false)
		setPage({
			pageNum: 1,
			pageSize: pagination.pageSize
		})
		pageReq.current = submit
	}
	useEffect(() => {
		if (!needSubmit) {
			setNeedSubmit(true)
			return
		}
		if (pageReq) pageReq.current(pagination)
	}, [pagination.pageNum, pagination.pageSize])
	return { pagination, onPageChange, resetPagination }
}

export default usePagination
